document.addEventListener('DOMContentLoaded', function() {
    const messageDiv = document.getElementById('message');
    const accountsTableBody = document.getElementById('accountsTable').getElementsByTagName('tbody')[0];
    const current_id = getCookie("id");

    async function fetchAccounts(params) {
        const query = new URLSearchParams(params).toString();
        const response = await fetch(`/accounts/search?${query}`);
        if (response.ok) {
            return await response.json();
        } else {
            throw new Error('Не удалось загрузить список аккаунтов.');
        }
    }

    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }

    function renderAccounts(accounts) {
        accountsTableBody.innerHTML = '';
        accounts.forEach(account => {
            const row = accountsTableBody.insertRow();
            ['id', 'firstName', 'lastName', 'email'].forEach(field => {
                const cell = row.insertCell();
                const input = document.createElement('input');
                input.type  = 'text';

                input.value = account[field];
                input.disabled = false;

                input.id   = field;
                input.name = field;

                cell.appendChild(input);
            });

            const actionsCell = row.insertCell();
            const deleteBtn = document.createElement('button');
            deleteBtn.textContent = '❌';
            deleteBtn.title = 'Удалить аккаунт';
            deleteBtn.onclick = () => deleteAccount(account.id);
            deleteBtn.disabled = (account["id"].toString() != current_id.toString());
            

            const updateBtn = document.createElement('button');
            updateBtn.textContent = '✔️';
            updateBtn.onclick = () => updateAccount(account.id, row);

            actionsCell.appendChild(updateBtn);
            actionsCell.appendChild(deleteBtn);

            row.ondblclick = () => row.querySelectorAll('input').forEach(input => input.disabled = false);
        });
    }

    async function deleteAccount(id) {
        try {
            const response = await fetch(`/accounts/${id}`, {
                method: 'DELETE'
            });
            if (response.ok) {
                window.location.href = '/';
            } else {
                showMessage('Ошибка удаления аккаунта: ' + (await response.json()).detail, 'error');
            }
        } catch (error) {
            showMessage('Ошибка удаления аккаунта: ' + error.message, 'error');
        }
    }

    async function updateAccount(id, row) {
        const data = {
            firstName: row.cells[1].querySelector('input').value,
            lastName:  row.cells[2].querySelector('input').value,
            email:     row.cells[3].querySelector('input').value,
            password:  '-',
        };

        try {
            const response = await fetch(`/accounts/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            if (response.ok) {
                showMessage('Аккаунт обновлен успешно.', 'success');
                searchAccounts();
            } else {
                showMessage('Ошибка обновления аккаунта: ' + (await response.json()).detail, 'error');
            }
        } catch (error) {
            showMessage('Ошибка обновления аккаунта: ' + error.message, 'error');
        }
    }

    function showMessage(message, type) {
        messageDiv.textContent = message;
        messageDiv.className = `message ${type}`;
        messageDiv.style.display = 'block';
        setTimeout(() => {
            messageDiv.style.display = 'none';
        }, 5000);
    }

    window.searchAccounts = async function() {
        const form = document.getElementById('filterForm');
        const formData = new FormData(form);
        
        const params = Object.fromEntries(formData.entries());

        try {
            const accounts = await fetchAccounts(params);
            renderAccounts(accounts);
        } catch (error) {
            showMessage(error.message, 'error');
        }
    };
});